#1.对验证码进行识别
#2.对post进行请求
#3.对数据进行持久化存储

#该网址已经停止维护，无法进行测试，仅学习思维方法
#使用古诗文网进行模拟登录，未达到预期效果

import requests
from lxml import etree
from SimulateLogin.chaojiying import Chaojiying_Client

#识别验证码的功能函数
def getCodeText(path):
    result = None
    chaojiying = Chaojiying_Client('15178530907', '340223wys', '952786')
    im = open(path, 'rb').read()
    result = chaojiying.PostPic(im, 1902)["pic_str"]
    print(result)
    return result


if __name__ == '__main__':
    #创建一个session对象，session请求和request请求一样的，只是session会自动携带cookie请求
    session = requests.Session()
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
                      ' Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.76'
    }
    url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'
    page_text = requests.get(url = url,headers=headers).text
    tree = etree.HTML(page_text)
    code_src = 'https://so.gushiwen.cn/'+tree.xpath('//*[@id="imgCode"]/@src')[0]
    code_img_data = requests.get(url = code_src,headers=headers).content#抓取到验证码的图片
    with open('./code.jpg','wb') as fp:
        fp.write(code_img_data)
    code = getCodeText('./code.jpg')#识别到验证码

    #post请求的发送
    login_url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'
    data ={

        'email':'15178530907',
        'pwd': '340223wys',
        'code': code,
        'denglu': '登录',

    }
    #使用session对象对post请求发送
    response = session.post(url = login_url,headers=headers,data=data)
    #响应状态码为200是表示模拟登录成功
    print(response.status_code)
    # logon_page_text = response.text
    # with open('gwc.html','w',encoding='utf-8') as fp:
    #     fp.write(logon_page_text)
    #爬取用户个人主页的数据
    datail_url = 'https://so.gushiwen.cn/user/collect.aspx'

    # 手动获取cookie，去网页寻找后粘贴复制
    # headers = {
    #     'Cookie' : 'xxxxxx'
    # }
    #使用session对象
    datail_page_text = requests.get(url = datail_url,headers=headers).text
    with open('wys.html','w',encoding='utf-8') as fp:
        fp.write(datail_page_text)


    #cookie来自模拟登录post请求之后，有服务器端创建

    #session会话
    # 1.可以进行请求的发送
    # 2.如果请求中产生的cookie，则该cookie会被自动存储在session对象中

    #1.使用session对象进行模拟请求的发送（cookie会被存储在session中，，，，
    # session对象对需要的页面进行请求发送，此时携带了cookie
    #

